package xyz.robinbingo.turing.dubbo.common.protocol.http;

import org.apache.commons.io.IOUtils;
import xyz.robinbingo.turing.dubbo.common.registry.Commons;
import xyz.robinbingo.turing.dubbo.common.protocol.invocation.Invocation;
import xyz.robinbingo.turing.dubbo.common.serialize.Serializer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * CustomDispatcherServletHandler
 *
 * @author Robin
 * @date 2021/1/29 下午2:36
 **/
public class CustomDispatcherServletHandler {

    public void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Invocation invocation = Serializer.deserialize(req.getInputStream(), Invocation.class);

            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class[] paramTypes = invocation.getParamTypes();
            Object[] params = invocation.getParams();

            Class<?> clazz = Commons.getClass(interfaceName);
            Method method = clazz.getMethod(methodName, paramTypes);
            Object o = clazz.getDeclaredConstructor().newInstance();
            Object invoke = method.invoke(o, params);

            ServletOutputStream out = resp.getOutputStream();
            IOUtils.write(String.valueOf(invoke), out, StandardCharsets.UTF_8);
        } catch (IOException | NoSuchMethodException | IllegalAccessException
                | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
